import 'dart:async';

import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/before_browser.dart';
import 'package:aichat_flutter_wallet/module_common/bridge/native_channel_bridge.dart';
import 'package:aichat_flutter_wallet/module_common/router/routers.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_api.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/sp.dart';
import 'package:lib_network/lib_network.dart';
import 'package:lib_util/lib_util.dart';
import 'package:shimmer/shimmer.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../model/dapp_model.dart';
import '../../provider/dapp_provider.dart';
import '../common.dart';

class DAppBannerComp extends StatefulWidget {
  const DAppBannerComp({
    super.key,
  });

  @override
  _DAppBannerState createState() => _DAppBannerState();
}

class _DAppBannerState extends State<DAppBannerComp> {
  final PageController _bannerPageController = PageController(keepPage: true);

  int _currentPage = 0;
  Timer? _timer;

  @override
  void dispose() {
    // 取消定时器
    _cancelTimer();
    _bannerPageController.dispose();
    super.dispose();
  }

  void _startTimer(int duration, int bannersLength) {
    if (_timer != null) {
      _cancelTimer();
    }
    _timer = Timer.periodic(Duration(milliseconds: duration), (_) {
      if (bannersLength > 0 && _bannerPageController.positions.isNotEmpty) {
        _bannerPageController.nextPage(
            duration: const Duration(milliseconds: 600), curve: Curves.ease);
      }
    });
  }

  void _cancelTimer() {
    _timer?.cancel();
  }

  Widget getBannerWidget(BuildContext context, DappBannerModel banner) {
    return InkWell(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: PublicImage(
          defaultImage: 'assets/images/dapp/default_banner.png',
          image: banner.showImages,
          width: double.infinity,
          height: double.infinity,
        ),
      ),
      onTap: () {
        try {
          // 内部链接
          if (banner.eventType.toString() == '1') {
            //非Dapp页面
            if (banner.clickEvent.toStringAsFixed(0) == '1') {
              if (RoutesList.isFlutterPage(banner.pageAddress)) {
                Routes.router!.navigateTo(
                    context, RoutesList.FlutterVal(banner.pageAddress));
              } else
                NativeChannelBridge().openNativePage(banner.pageAddress);
            } else if (banner.clickEvent.toStringAsFixed(0) == '2') {
              //Dapp页面
              doGotoBrowser(context: context, webUrl: banner.pageAddress);
            } else
              return;
          } else {
            launchUrl(Uri.parse(banner.pageAddress));
          }
        } catch (err) {
          print(err);
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DAppProvider>(builder: (c, model, topWidget) {
      var bannersLength = model.banners.length;
      var isBannerLoading = model.isBannerLoading;
      if (_bannerPageController.positions.isNotEmpty) {
        _bannerPageController.jumpToPage(0);
      }

      _startTimer(model.bannersDuration, model.banners.length);
      return Container(
        height: 100.w,
        width: double.infinity,
        margin: EdgeInsets.only(left: 20, right: 20),
        child: Stack(
          children: [
            if (!isBannerLoading && bannersLength > 0)
              ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: PageView.builder(
                    onPageChanged: (int page) {
                      _currentPage = page;
                      _startTimer(model.bannersDuration, model.banners.length);
                    },
                    controller: _bannerPageController,
                    itemBuilder: (context, index) {
                      return getBannerWidget(
                          context, model.banners[index % bannersLength]);
                    },
                    // itemCount: bannerList.length,
                  )),
            if (!isBannerLoading && bannersLength > 0)
              Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  height: 3.w,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(255, 255, 255, .5),
                    borderRadius: BorderRadius.circular(6),
                  ),
                  margin: const EdgeInsets.only(bottom: 10),
                  child: ThemePageIndicator(
                    count: model.banners.length,
                    controller: _bannerPageController,
                  ),
                ),
              ),
            if (!isBannerLoading && bannersLength == 0)
              Container(
                width: double.infinity,
                child: Image.asset(
                  'assets/images/dapp/default_banner.png',
                  fit: BoxFit.cover,
                ),
              ),
            if (isBannerLoading)
              Positioned(
                  left: 0,
                  top: -1,
                  right: 0,
                  child: Shimmer.fromColors(
                    baseColor: Color.fromRGBO(246, 246, 246, 1),
                    highlightColor: Colors.grey.shade300,
                    child: Container(
                      width: double.infinity,
                      height: 150.w,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        color: Colors.grey,
                      ),
                    ),
                  )),
          ],
        ),
      );
    });
  }
}
